<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/5/22 0022
 * Describe: 用户信息管理类.
 */
namespace app\api\controller\lishidai;
use app\common\controller\Fengkong;
use app\common\model\User as userModel;
use app\common\model\System;
use think\Db;
use app\common\controller\order\Orderget;

class User extends Base
{
    /**
     * 用户过滤v2.
     */
    public function isUserAccept()
    {
        //验证参数
        $postData = input('');
        $data = json_decode($postData['args'], 1);
        $result = $this->validate($data, 'User.isUserAccept');
        if ($result !== true) {
            errorResult($result);
        }
        //获取用户信息 新人直接通过 并返回默认产品额度
        $userModelObj = new userModel();
        $systemModelObj = new System();
        $userInfo = $userModelObj->getUserInfo($data);
        $minGoods = model('Order')->getMinGoods();
        if (!$userInfo) {
            $temp = [
                'result' => 200, //借款的权限 立时贷体统权限值 200可以借款 301用户年龄过大或过小 401用户在机构有未完成的借款 402用户在机构有不良借款记录 403该用户是征信系统黑名单用户 505其他原因，禁止用户借款。需在备注说说明原因
                'user_status' => 1, //立时贷提供 1新用户 2老用户
                'amount' => $minGoods * 100, //最大可贷额度，单位: 分
                'min_amount' => $minGoods * 100, //最小可贷额度，单位: 分
                'terms' => [7], //可贷期限。如: [7,14,30]
                'term_type' => 1, //贷款期限单位。1:按天; 2：按月; 3：按年
                'loan_mode' => 0, //立时贷未有说明字段
            ];
            successResult($temp);
        }
        //检测用户状态 是否是黑名单等
        if (!$userModelObj->isUserStatus($userInfo)) {
            errorResult($userModelObj->getError(), 1, ['result' => 403, 'remark' => $userModelObj->getError()]);
        }

        //检测用户年龄
        if (!$userModelObj->isUserAge($userInfo)) {
            errorResult($userModelObj->getError(), 1, ['result' => 301, 'remark' => $userModelObj->getError()]);
        }
        //检测用户是否有逾期订单
        if ($userModelObj->getUserOverdueOrder($userInfo['ID'])) {
            errorResult($userModelObj->getError(), 1, ['result' => 402, 'remark' => $userModelObj->getError()]);
        }

        //检测用户是否有进行中的订单
        if ($userModelObj->getUserOrder($userInfo['ID'])) {
            errorResult('用户有进行中的订单', 1, ['result' => 401, 'remark' => '用户有进行中的订单']);
        }

        //检测上笔订单是否被拒，被拒返回剩余可再次借款时间提醒
        $result = $userModelObj->isUserRefuseOrder($userInfo['ID']);
        if ($result !== false) {
            errorResult($result, 1, ['result' => 505, 'can_loan_time' => $result, 'remark' => '你已有一笔被拒绝订单，请于'.$result.'后再次申请']);
        }

        //获取用户可借款金额
        $data = $userModelObj->getLoanMoney($userInfo['ID']);
        if ($data === false) {
            errorResult($userModelObj->getError(), 1, ['result' => 505, 'remark' => $userModelObj->getError()]);
        }
        $temp = [
            'result' => 200, //借款的权限 立时贷体统权限值 200可以借款 301用户年龄过大或过小 401用户在机构有未完成的借款 402用户在机构有不良借款记录 403该用户是征信系统黑名单用户 505其他原因，禁止用户借款。需在备注说说明原因
            'user_status' => 2, //立时贷提供 1新用户 2老用户
            'amount' => max($data) * 100, //最大可贷额度，单位: 分
            'min_amount' => $minGoods * 100, //最小可贷额度，单位: 分
            'terms' => [7], //可贷期限。如: [7,14,30]
            'term_type' => 2, //贷款期限单位。1:按天; 2：按月; 3：按年
            'loan_mode' => 0, //立时贷未有说明字段
        ];
        successResult($temp);
    }

    /**
     * 推送用户基础信息 (立时贷 一推)
     * Order.pushUserBaseInfo
     * order_info  订单
     * user_info  基础
     * user_verify 认证
     * 运营商原始数据   通话记录
     * 运营商报告  通话排行
     * $UserID  用户ID
     * 程序执行的操作   1写入 手机认证表  身份证认证表  运营商原始数据表  运营商报告表   修改用户表的信息  手机和运营商认证 状态以及个人资料(姓名 手机号 身份证号码之类的).
     */
    public function pushUserBaseInfo()
    {
        //验证参数
        $args = input('args');
        $str = base64_decode($args);
        $args = gzdecode($str);
        $args = json_decode($args, true);
        $orderParam = $args['order_info']; // 订单信息
        $userParam = $args['user_info']; //基础信息
        $userverify = $args['user_verify']; //认证信息
        $yuanshi = $userverify['moxie_original_operator_verify']['moxie_operate_verify']; //魔蝎原始数据
        $baogao = $userverify['moxie_original_operator_report_verify']['moxie_operate_report_verify']; //魔蝎运营商报告
        $calls = $yuanshi['calls']; //魔蝎原始数据 中的通话记录
        $callsxin = [];
        foreach ($calls as $k => $v) {
            foreach ($v['items'] as $kk => $vv) {
                $callsxin[] = $vv;
            }
        }
        $calls = $callsxin;
        $TongoHuaPaiHang = $baogao['call_contact_detail']; //魔蝎运营商报告中的  通话排行
        $youdun = $userverify['idcard_info']; //有盾数据
        Db::startTrans();
        try {
            //检测用户是否存在 不存在既注册
            $isUser = Db::table('xb_mem_info')->where('Mobile', $userParam['user_phone'])->find();
            if (!$isUser) {
                $addUserData = [
                    'TrueName2' => $userParam['user_name'],
                    'Mobile' => $userParam['user_phone'],
                    'IDCard' => $userParam['user_idcard'],
                    'RegTime' => date('Y-m-d H:i:s'),
                    'UserName' => $userParam['user_phone'],
                    'Mobile' => $yuanshi['mobile'], //手机号码
                    'TrueName2' => $yuanshi['name'], //手机姓名
                    'TrueName' => $youdun['idcard_info']['ocr_name'], //身份证姓名
                    'IDCard' => $youdun['idcard_info']['ocr_id_number'], //身份证号码
                    'isID' => '1', //身份证认证状态
                    'isMobile' => '1', //手机认证状态
                    'Sex' => $youdun['idcard_info']['ocr_sex'], //性别
                    'TgadminID' => model('TgAdmin')->getChannelInfo('立时贷','ID')['ID']??1, //渠道ID  L立时代的渠道ID固定为4
                    'LimitBalcance' => db('goods')->where(['defont'=>'1','IsShelves'=>'1'])->value('LimitBalcance'), // 立时贷用户默认授信额度
                ];
                $result = db('mem_info')->insertGetId($addUserData);
                $userId = $result;
            } else {
                $userId = $isUser['ID'];
            }
            //写入用户借款订单
            //根据订单金额获取接单产品信息
            $goods = model('order')->getMoneyOrderInfo($orderParam['loan_amount'] / 100);
            //检测用是新客老客
            $isNewUser = db('loans_applylist')->where('UserID', $userId)->value('ID');
            //检测用户是首借复借
            $isFirst = db('loans_applylist')->where(['UserID' => $userId, 'LoanStatus' => 3])->value('ID');
            //检测推送订单单号是否已存在
            $isOrder = db('loans_applylist')->where('OrderSn', $orderParam['order_sn'])->value('ID');
            if ($isOrder) {
                throw new \Exception('推送重复的订单单号 '.$orderParam['order_sn']);
            }
            $Orderget = new Orderget();
            $ApplyDay = $orderParam['loan_term'] - 1; //借款期限减一
            $addOrder = [
                'OrderSn' => $orderParam['order_sn'], //订单编号
                'ApplyMoney' => $orderParam['loan_amount'] / 100, //借款金额(单位:分)
                'AdoptMoney' => $goods['daozhang'], //到账金额
                'Interest' => $goods['GuanliCost'], //服务费
                'daoqiMoney' => $goods['daoqiyinghua'], //到期应还
                'zhanqifei' => $goods['zhanqifei'], //展期费
                'yuqililv' => $goods['yuqulv'], //逾期利率
                'ApplyDay' => $orderParam['loan_term'], //string	是	借款期限
                'term_type' => $orderParam['term_type'], //期限类型(1: 按天; 2: 按月; 3: 按年;)
                'LoanStatus' => '0', //订单状态0申请中 1等待放款 2已放款 3已完成 4已取消 5已拒绝 6等待银行打款 7待人工审核
                'ApplyTime' => date('Y-m-d H:i:s'), //订单申请时间
                'UserID' => $userId,
                'ProductID' => $goods['ID'], //商品ID
                'user_type' => ($isNewUser) ? 2 : 1, //是否新老客
                'app_type' => ($isFirst) ? 2 : 1, //是否首借复借
                'YyFkTime' => $Orderget->get_time(date('Y-m-d H:i:s'), $ApplyDay), //预约还款时间
            ];

            //			p($addOrder);die;
            db('loans_applylist')->insert($addOrder);
            //检测用户是否有原始魔蝎数据 有更新 无添加
            $origin = db('moxie_origin')->where('UserID', $userId)->find();
            if ($origin) {
                $aaa['OriginData'] = json_encode($yuanshi, 1);
                $aaa['calls'] = json_encode($calls, 1);
                $aaa['UpdateTime'] = date('Y-m-d H:i:s');
                Db::table('xb_moxie_origin')->where('UserID', $userId)->update($aaa);
            } else {
                $aaa['CreateTime'] = date('Y-m-d H:i:s');
                $aaa['OriginData'] = json_encode($yuanshi, 1);
                $aaa['calls'] = json_encode($calls, 1);
                $aaa['UserID'] = $userId;
                Db::table('xb_moxie_origin')->insertGetId($aaa);
            }
            //检测用户是否有原始运营商数据 有更新 无添加
            $report = Db::table('xb_moxie_report')->where('UserID', $userId)->find();
            if ($report) {
                $bbb['ReportData'] = json_encode($baogao, 1);
                $bbb['TongoHuaPaiHang'] = json_encode($TongoHuaPaiHang, 1);
                $bbb['UpdateTime'] = date('Y-m-d H:i:s');
                Db::table('xb_moxie_report')->where('UserID', $userId)->update($bbb);
            } else {
                $bbb['CreateTime'] = date('Y-m-d H:i:s');
                $bbb['ReportData'] = json_encode($baogao);
                $bbb['TongoHuaPaiHang'] = json_encode($TongoHuaPaiHang, 1);
                $bbb['UserID'] = $userId;
                Db::table('xb_moxie_report')->insertGetId($bbb);
            }
            //检测用户是否有手机认证表 有更新 无添加
            $renzen_mobile = Db::table('xb_renzen_mobile')->where('UserID', $userId)->find();
            if ($renzen_mobile) {
                $ddd = [
                    'ZUserName' => $yuanshi['name'], //手机姓名
                    'Status' => 1,
                    'mobile' => $yuanshi['mobile'], //手机号码
                    'UpdateTime' => date('Y-m-d H:i:s'),
                ];
                Db::table('xb_renzen_mobile')->where('UserID', $userId)->update($ddd);
            } else {
                $ddd = [
                    'ZUserName' => $yuanshi['name'], //手机姓名
                    'mobile' => $yuanshi['mobile'], //手机号码
                    'RenzTime' => date('Y-m-d H:i:s'),
                    'UserID' => $userId,
                     'Status' => 1,
                ];
                Db::table('xb_renzen_mobile')->insertGetId($ddd);
            }
            //检测用户是否身份认证 有更新 无添加
            $cards = Db::table('xb_renzen_cards')->where('UserID', $userId)->find();
            $img = [
                'CardFace' => $youdun['idcard_info']['id_number_z_picture'], //正面
                'CardSide' => $youdun['idcard_info']['id_number_f_picture'], //反面
                'Cardschi' => $youdun['idcard_info']['id_number_picture'], //人脸
            ];
            //遍历移动用户身份证图片信息等
            foreach ($img as $k => $val) {
                $imgName = 'userId'.$userId.'.'.pathinfo($val, PATHINFO_EXTENSION);
                $cccs[$k] = './youdun/img/'.$k.$imgName;
//              file_put_contents('./youdun/img/'.$k.$imgName, file_get_contents($val));
            }
            if ($cards) {
                $ccc = [
                    'Status' => 1,
                    'IDCard' => $youdun['idcard_info']['ocr_id_number'],
                    'Name' => $youdun['idcard_info']['ocr_name'],
                    'UpdateTime' => date('Y-m-d H:i:s'),
                ];
                $ccc = array_merge($ccc, $cccs);
                Db::table('xb_renzen_cards')->where('UserID', $userId)->update($ccc);
            } else {
                $ccc = [
                    'RenzTime' => date('Y-m-d H:i:s'),
                    'UserID' => $userId,
                    'Status' => 1,
                    'IDCard' => $youdun['idcard_info']['ocr_id_number'],
                    'Name' => $youdun['idcard_info']['ocr_name'],
                ];
                $ccc = array_merge($ccc, $cccs);
                Db::table('xb_renzen_cards')->insertGetId($ccc);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            //写入错误日志
            \Think\Log::record('立时贷 一推推送失败错误日志 '.$e->getMessage());
            errorResult('推送失败', 1, ['remark' => $e->getMessage()]);
        }
        successResult([], '推送成功', 200);
    }

    /**
     * 推送用户补充信息 (立时贷 二推)
     * Order.pushUserAdditionalInfo
     * order_info	object	是	用户订单信息
     * user_additional	object	是	用户补充信息
     * 订单信息存到订单表 (立时代数据  根据立时代借款金额 获取产品表goods里面的产品详情)
     * 存入社交认证表 xb_renzen_social.
     * address_book  address_book 通讯录信息.
     */
    public function pushUserAdditionalInfo()
    {
        $args = input('args');
        $args = json_decode($args, true);
        $user_additional = $args['user_additional']; //用户补充信息
        //根据订单单号获取用户ID
        $orderData = model('Order')->getIdOrderInfo($args['order_info']['order_sn']);
        if (!$orderData) {
            errorResult('推送失败', 1, ['remark' => '推送的订单编号不存在']);
        }
        Db::startTrans();
        try {
            //检测用户社交信息是否存在 存在执行更新 否者写入数据库
            $isUserSocial = db('renzen_social')->where('UserID', $orderData['UserID'])->value('ID');
            //		        通讯录数据重组
            $aaa = [];
            foreach ($user_additional['address_book']['phone_list'] as $k => $v) {
                $v = explode('_', $v);
                if (empty($v['0'])) {
                    $a['contact_name'] = '空空';
                } else {
                    $a['contact_name'] = $v['0'];
                }
                $a['contact_phone'] = $v['1'];
                $aaa[] = $a;
            }
            if ($isUserSocial) {
                $socialData = [
                    'ID' => $isUserSocial,
                    'UserID' => $orderData['UserID'],
                    'Phonelist' => json_encode($aaa, JSON_UNESCAPED_UNICODE), //通讯录
                    'Status' => '1', //状态:0待审核 1已认证 2认证失败
                    'UpdateTime' => date('Y-m-d H:i:s'), //认证时间
                    'qq' => $user_additional['qq']['qq'], //qq号码
                    'marry' => $this->getMarriage($user_additional['marriage']['marriage']), // 婚姻状态 1 未婚 2 已婚 3 离异 4 已婚未育 5 丧偶 6 其他
                    'xueli' => $this->getEducation($user_additional['education_info']['degree']), // 学历 教育程度 5博士及以上 4 硕士 3 本科 2大专 1中专/高中及以下
                    'address' => $user_additional['work_office_info']['company_name'], // 地址
                    'ad_detail' => $user_additional['work_office_info']['company_address'], // 详细地址
                    'person_one' => $user_additional['contact_info']['name'], // 紧急联系人1
                    'person_one_mobile' => $user_additional['contact_info']['mobile'], // 紧急联系人1电话
                    'r1' => $this->getRelationship($user_additional['contact_info']['relation']), // 紧急联系人1关系
                    'person_two' => $user_additional['contact_info']['name_spare'], // 紧急联系人2
                    'person_two_mobile' => $user_additional['contact_info']['mobile_spare'], // 紧急联系人2电话
                    'r2' => $this->getRelationship($user_additional['contact_info']['relation_spare']), // 紧急联系人2关系
                ];
                Db::table('xb_renzen_social')->where(['UserID' => $orderData['UserID']])->Update($socialData);
            } else {
                $socialData = [
                    'UserID' => $orderData['UserID'],
                    'Phonelist' => json_encode($aaa, JSON_UNESCAPED_UNICODE), //通讯录
                    'Status' => '1', //状态:0待审核 1已认证 2认证失败
                    'RenzTime' => date('Y-m-d H:i:s'), //认证时间
                    'qq' => $user_additional['qq']['qq'], //qq号码
                    'marry' => $this->getMarriage($user_additional['marriage']['marriage']), // 婚姻状态 1 未婚 2 已婚 3 离异 4 已婚未育 5 丧偶 6 其他
                    'xueli' => $this->getEducation($user_additional['education_info']['degree']), // 学历 教育程度 5博士及以上 4 硕士 3 本科 2大专 1中专/高中及以下
                     'address' => $user_additional['work_office_info']['company_name'], // 地址
                    'ad_detail' => $user_additional['work_office_info']['company_address'], // 详细地址
                    'person_one' => $user_additional['contact_info']['name'], // 紧急联系人1 getRelationship
                    'person_one_mobile' => $user_additional['contact_info']['mobile'], // 紧急联系人1电话
                    'r1' => $this->getRelationship($user_additional['contact_info']['relation']), // 紧急联系人1关系
                    'person_two' => $user_additional['contact_info']['name_spare'], // 紧急联系人2
                    'person_two_mobile' => $user_additional['contact_info']['mobile_spare'], // 紧急联系人2电话
                    'r2' => $this->getRelationship($user_additional['contact_info']['relation_spare']), // 紧急联系人2关系
                ];
                $RE = Db::table('xb_renzen_social')->insert($socialData);
            }
            //检测会员社交认证状态是否已认证 没有认证便更新
            $isSocial = db('mem_info')->where('ID', $isUserSocial['UserID'])->value('isSocial');
            if ($isSocial != 1) {
                db('mem_info')->where('ID', $orderData['UserID'])->update(['isSocial' => 1]);
            }
            Db::commit();
            successResult([], '推送成功');
        } catch (\Exception $e) {
            Db::rollback();
            //写入错误日志
            \Think\Log::record('立时贷 二推推送失败错误日志 '.$e->getMessage());
            errorResult('推送失败', '', ['remark' => '推送失败']);
        }
    }

    //风控选择判断   1 滴滴 2 磨盘
    public function fengkong_xuanzai($sys_basicinfo, $userId, $data, $post)
    {
        if ($sys_basicinfo['fengkong'] == '1') {//调取滴滴风控系统返回的是分数
            $Fengkong = new Fengkong();
            $realScore = $Fengkong->fengkong_jiuwei($userId);
            $real = json_decode($realScore, 1);
            //		 $real['return_code']  0：成功  -1 ：失败
            if ($real['return_code'] != 0) {
                //		                       把错误的风控结果存入数据库
                $data['ShadminID'] = '119'; //审核员
                $data['LoanStatus'] = '5';
                $data['jishen'] = $real['return_info'];
                Db::table('xb_loans_applylist')->where(['UserID' => $data['UserID'], 'OrderSn' => $data['OrderSn']])->update($data);
                show_error_api($message = '滴滴风控系统调用失败');
                die;
            } else {
                return $realScore = $real['score']; //  风控分
            }
            //	            return $realScore='300';//测试用的 分控分
        } elseif ($sys_basicinfo['fengkong'] == '2') {//调用磨盘风控系统 返回的是结果
        //          获取客户类型
                $user_type = Db::table('xb_loans_applylist')->where(['LoanStatus' => '3', 'UserID' => $userId])->find();
            if ($user_type) {
                $user_type == '2'; //老客
            } else {
                $user_type == '1'; //新客
            }
            $mopan = new MoPan();
            //				$data['OrderSn']='12345';
            $realScore = $mopan->getMoPanIntegral($userId, $data['OrderSn'], $post['MobileType'], $user_type, $data['ApplyMoney'], $data['ApplyTime']);
            $realScore = json_decode($realScore, 1);
            if ($realScore['code'] == '000000') {
                return $realScore['code'];
            } else {
                Db::table('xb_loans_applylist')->where(['UserID' => $data['UserID'], 'OrderSn' => $data['OrderSn']])->update(['jishen' => $realScore['code']]);
                show_error_api($message = '磨盘风控系统调用失败');
                show_error_api($realScore['msg']);
            }
        }
    }

//      风控开关  1开启 2关闭
//      开启  新客户老客户都调用风控
//      关闭  新客户调用  老客户走根据静默时间和借款次数判断是否调用
    public function fengkong($sys_basicinfo, $userId, $data, $post)
    {
        if ($sys_basicinfo['fengkong_kaiguan'] == '1') {//全部调用风控
            return $this->fengkong_xuanzai($sys_basicinfo, $userId, $data, $post);
        } elseif ($sys_basicinfo['fengkong_kaiguan'] == '2') {//新客户调用  老客户走根据静默时间和借款次数判断是否调用
            $kehuleixing = Db::table('xb_loans_applylist')->where(['LoanStatus' => '3', 'UserID' => $userId])->order('ID desc')->find();
            if ($kehuleixing) {//老客户
                //				查询静默时间
                $SjFkTime = strtotime($kehuleixing['SjFkTime']);
                $days = $sys_basicinfo['fengkong_time'];
                $time = 86400 * $days;
                $SjFkTime = $SjFkTime + $time;
                //				借款次数
                $count = Db::table('xb_loans_applylist')->where(['LoanStatus' => '2', 'UserID' => $userId])->count();
                if ($SjFkTime > time() && $count < $sys_basicinfo['fengkong_nums']) {
                    return '免审核';
                } else {
                    return $this->fengkong_xuanzai($sys_basicinfo, $userId, $data, $post);
                }
            } else {
                return $this->fengkong_xuanzai($sys_basicinfo, $userId, $data, $post);
            }
        }
    }

    /**
     * 订单调用风控
     * $UserID  用户ID.
     * $OrderSn   订单号码
     */
    public function shenhe($OrderSn = 'KY656940458450141184')
    {
            $sys_basicinfo = Db::table('xb_sys_basicinfo')->find(); //调取系统配置
            $data = Db::table('xb_loans_applylist')->where(['OrderSn' => $OrderSn])->find(); //订单所有数据
            $UserID = $data['UserID']; //用户ID
            $orderId = $data['ID']; //订单ID
            $realScore = $this->fengkong($sys_basicinfo, $UserID, $data, $post = '1'); //走风控流程
//          if($UserID=='2190'){
//            $realScore = '607.21111498373'; //测试风控风
//          }
            if ($realScore === '免审核') {//如果等于免审核说明没有调用风控   就去找该用户上一次订单的风控结果
                 $songsong = Db::table('xb_loans_applylist')->where('ID', $UserID)->order('ID DESC')->find();
                $data['jishen'] = $songsong['jishen'];
                $data['ShadminID'] = '119'; //机器审核客服
                $data['LoanStatus'] = '1';
            } elseif ($realScore === '000000') {//此时调用了 磨盘 进入等待人工审核  等待磨盘回调更改订单状态
                $data['LoanStatus'] = '0';
                $data['jishen'] = $realScore; //机器审核结果//此时 调用了 滴滴风控 根据分数 判断订单状态
            } else {
                $data['jishen'] = $realScore; //机器审核结果//此时 调用了 滴滴风控 根据分数 判断订单状态
                //获取此用户渠道
                $TgadminID = Db::table('xb_mem_info')->where('ID', $UserID)->value('TgadminID');
                if (!$TgadminID) {
                    show_error_api($message = '查询用户渠道异常');
                }
                $fenkongfen = Db::table('xb_tg_admin')->where('ID', $TgadminID)->find(); //渠道分
                $jishenfen = $fenkongfen['jishenfen'];
                $rengongfen = $fenkongfen['rengongfen'];
                if ($jishenfen == 0 && $rengongfen == 0) {
                    $xitongfengkong = Db::table('xb_sys_basicinfo')->find();
                    if (empty($xitongfengkong['rengongfen'])) {
                        show_error_api($message = '系统分设置异常');
                    } else {
                        $jishenfen = $xitongfengkong['jishenfen']; //机审核分
                        $rengongfen = $xitongfengkong['rengongfen']; //人工分
                    }
                }
                //      如果风控分小于人工分  直接拒绝
                if ($realScore < $rengongfen) {
                    $data['ShadminID'] = '119'; //审核员
                    $data['LoanStatus'] = '5';
					$data['fail_reason'] = '审核失败拒绝订单'; //审核结果
                }
                //        如果风控分大于机审分 直接通过 自动放款
                if ($realScore >= $jishenfen) {
                    $data['ShadminID'] = '119'; //审核员
                    $data['FkadminID'] = '125'; //放款专员
                    $data['LoanStatus'] = '1';
					$data['fail_reason'] = '等待用户确认用款'; //审核结果
				
                }
                //      如果风控大于等于人工  小于等于机审分  进入待审核状态
                if ($realScore >= $rengongfen && $realScore < $jishenfen) {
                    $data['LoanStatus'] = '7';
                    $DShadminID = Db::table('xb_sys_administrator')->where('RoleID', '55')->column('ID'); //渠道分
                    $num = count($DShadminID) - 1;
                    $DShadminID = $DShadminID[rand(0, $num)];
                    $data['ShadminID'] = $DShadminID;
					$data['fail_reason'] = '等待人工审核'; //审核结果
                }
            }
        //			更新走完风控得订单
             $data['ShTime'] = date('Y-m-d H:i:s'); //审核时间
             $Orderget = new Orderget();
             $ApplyDay = $data['ApplyDay'] - 1; //借款期限减一
             $data['YyFkTime'] = $Orderget->get_time(date('Y-m-d H:i:s'), $ApplyDay); //预约还款时间
             $orderIup = Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data);
//			 审批成功 和失败推送里时代 待审核不推送
             if($data['LoanStatus']=='5' || $data['LoanStatus']=='1'){
		        //			审批结果回调 立时代
		        $songsong = new Songsong();
				$Orderget=new Orderget();
	            $time=$Orderget->get_time(date('Y-m-d H:i:s'),7);//获取系统高配置数据
				$data['can_loan_time']=$time;
		        $re = $songsong->approveFeedback($data); //审批结果回调接口
		//      立时代审批结果回调写入数据库 订单表
		        Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update(['lishidai_shenpi' => $re]);
				echo '审核失败或者成功';
		        die;
             }else{
				 Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update(['lishidai_shenpi' => '等待人工审核  暂时不推送']);
				 	echo '等待人工审核';
				 die;
             }
    }

    /**
     * 绑卡之后的流程    给立时代返回返回信息  走风控审核信息
     * $UserID  用户ID.
     * $OrderSn   订单号码
     */
    public function shuimian($UserID, $order_sn)
    {
        $reuslt = array(
                           'status' => '1',
                           'message' => 'success',
                           'response' => [
                           'bind_status' => '200',
                           'remark' => '绑卡成功',
                           ],
                    );
        Db::table('xb_mem_info')->where('ID', $UserID)->update(['Status' => '2']);
        echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
        //			   这里调用风控 去审核订单  小睡一会
        $size = ob_get_length();
        header("Content-Length: $size");
        header('Connection: close');
        header('HTTP/1.1 200 OK');
        header('Content-Type: application/json;charset=utf-8');
        ob_end_flush();
        if (ob_get_length()) {
            ob_flush();
        }
        flush();
        if (function_exists('fastcgi_finish_request')) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
                    fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true); //在关闭连接后，继续运行php脚本
                set_time_limit(0); //no time limit，不设置超时时间（根据实际情况使用）
                //继续运行的代码
                sleep(10);
        $re = $this->shenhe($order_sn);
    }

    /**
     * 绑卡流程
     * BindCard.applyBindCard.
     */
    public function applyBindCard()
    {
        $data_post = input();
        $args = $data_post['args'];
        $args = json_decode($args, 1);
        $UserID = Db::table('xb_loans_applylist')->where('OrderSn', $args['order_sn'])->value('UserID'); //通过订单号查找
        if (!$UserID) {
            errorResult('', '', ['bind_status' => 999, 'remark' => '订单号为'.$args['order_sn'].'的用户信息不存在']);
        } else {
            $renzen_bank = Db::table('xb_renzen_bank')->where(['UserID' => $UserID, 'BankNo' => $args['card_number']])->find();
            if ($renzen_bank) {
                $this->shuimian($UserID, $args['order_sn']);
                die;
            }
        }
        $data['MobNo'] = $args['card_phone']; //手机号码  绑卡的手机号码
               $data['IDNo'] = $args['user_idcard']; //身份证件号码
               $data['CstmrNm'] = $args['user_name']; //姓名
               $data['BkAcctNo'] = $args['card_number']; //卡号
               $data['MerUserId'] = $UserID; //用户ID
               $data['PartnerId'] = Db::table('xb_sys_inteparameter')->where(['ParaName' => 'changpay'])->value('ParaValue'); //商户号
               $changpay = new \changpay\ChangPay();
        if (!empty($args['verify_code'])) {
            $data['OriAuthTrxId'] = Db::table('xb_mem_info')->where('ID', $UserID)->value('TrxId'); //用户表查询   第一步获取验证码的时候存入
               $data['SmsCode'] = $args['verify_code']; //验证码
               $changpay = new \changpay\ChangPay();
            $datas = $changpay->bank2($data); //正式 绑卡 返回结果
            if ($datas['AcceptStatus'] == 'S') {
                $update['BankNo'] = $args['card_number']; //卡号
                   $update['BankName'] = (new Bank())->getCodeBankName($args['bank_code']); //银行卡名称    根据标号获取名称
                   $update['YMobile'] = $args['card_phone']; //手机号码 银行卡预留
                   //		绑定银行卡时间先看看以前有没有已经绑定的银行卡   如果有就先解除绑定  然后再操作
                   $renzheng_bank = Db::table('xb_renzen_bank')->where(['UserID' => $UserID, 'Status' => '1'])->find(); //获取银行卡信息
                   if ($renzheng_bank) {
                       $update['UpdateTime'] = date('Y-m-d H:i:s');
                       $result = Db::table('xb_renzen_bank')->where('UserID', $UserID)->update($update);
//                     $re_jiebang = $changpay->jiebang($renzheng_bank['BankNo'], $UserID, $data['PartnerId']);
                   } else {
                       $update['RenzTime'] = date('Y-m-d H:i:s');
                       $update['UserID'] = $UserID; //用户ID
                       $ret = Db::table('xb_renzen_bank')->insertGetId($update);
                       if ($ret) {
                           //修改用户表数据
                           $result = Db::table('xb_mem_info')->where('ID', $UserID)->update(['isBank' => '1']);
                       }
                   }
                $this->shuimian($UserID, $args['order_sn']);
                die;
            } else {
//             	  绑卡失败 给利时代 返回数据
                $reuslt = array(
                           'status' => '1',
                           'message' => 'success',
                           'response' => [
                           'bind_status' => '505',
                           'remark' => $datas['RetMsg'], //畅捷失败提示消息标识
                           ],
                        );
                exit(json_encode($reuslt, JSON_UNESCAPED_UNICODE));
            }
        } else {
            $datas = $changpay->bank1($data);
//			p($datas);die;
            if ($datas['AcceptStatus'] == 'S') {
//             	请求成功把档次请求的唯一标示 存入用户表
                Db::table('xb_mem_info')->where('ID', $UserID)->update(['TrxId' => $datas['TrxId']]);
                //				给利时代返回数据
                $reuslt = array(
                       'status' => '1',
                       'message' => 'success',
                       'response' => [
                       'bind_status' => '100',
                       'remark' => '验证码发送成功，请输入已发送的验证码重新绑卡', //提示信息
                       ],
                );
                exit(json_encode($reuslt, JSON_UNESCAPED_UNICODE));
            } else {
                $reuslt = array(
                       'status' => '1',
                       'message' => 'success',
                       'response' => [
                       'bind_status' => '505',
                       'remark' => $datas['RetMsg'], //畅捷失败提示消息标识
                       ],
                    );
                exit(json_encode($reuslt, JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * H5认证项以及用款确认查询.
     *
     * 立时贷提供类型字段
     * 认证类型 1 芝麻认证，2 运营商认证, 3 信用卡认证，4 公积金认证，5 社保认证，6 人行征信认证，7 信用卡账单认证 8 用款确认
     */
    public function authStatus()
    {
        //验证参数
        $param = input('');
        $postData = json_decode($param['args'], 1);
        $result = $this->validate($postData, 'User.authStatus');
        if ($result !== true) {
            errorResult($result);
        }

        $auth_result = '401'; //认证结果状态; 200 认证成功，401 未认证
        $success_time = 0; //有效期时间戳
        if ($postData['auth_type'] == 2) { //运营商的时候检查是否已认证 其它一律返回未认证 因为本系统没有其它认证项
            $data = db('mem_info')->alias('i')
                ->join('xb_renzen_mobile m', 'i.ID = m.UserID')
                ->where(['i.TrueName' => $postData['user_name'], 'i.Mobile' => $postData['user_phone'], 'i.IDCard' => $postData['user_idcard']])
                ->field('m.*')
                ->find();

            if ($data && $data['Status'] == 1) {
                $auth_result = '200';
                $success_time = '4102416001'; //2100-01-01 00:00:01
            }
        }

        $temp = [
            'auth_result' => $auth_result,
            'success_time' => $success_time,
        ];
        successResult($temp);
    }

    /**
     * 获取婚姻状态值 （立时贷 提供字段值）.
     *
     * @param int $status 状态值
     *
     * @return string 婚姻描述值
     *
     * 婚姻状态 1 未婚 2 已婚 3 离异 4 已婚未育 5 丧偶 6 其他
     */
    public function getMarriage($status)
    {
        $temp = [1 => '未婚', 2 => '已婚', 3 => '离异', 4 => '已婚未育', 5 => '丧偶', 6 => '其他'];
        if (isset($temp[$status])) {
            return $temp[$status];
        }

        return $temp[6];
    }

    /**
     * 根据学历字段值获取对象名称（立时贷 提供字段值）.
     *
     * @return int    $status 状态值
     * @return string 学历名称
     *
     * 教育程度 5博士及以上 4 硕士 3 本科 2大专 1中专/高中及以下 0小学(0立时贷未提供 此处作为未知字段填充)
     */
    public function getEducation($status)
    {
        $temp = ['小学', '中专/高中及以下', '大专', '本科', '硕士', '博士及以上'];

        if (isset($temp[$status])) {
            return $temp[$status];
        }

        return '小学';
    }

    /**
     * 获取联系人关系 (立时贷 提供字段值).
     *
     * @param int $status 状态值
     *
     * @return string 关系名称
     *
     * 编码&关系 1父亲 2配偶 3母亲 4子女 5同学 6朋友 7同事 8亲戚 9儿子 10女儿 11兄弟 12姐妹 100其他
     */
    public function getRelationship($status)
    {
        $temp = [1 => '父亲', 2 => '配偶', 3 => '母亲', 4 => '子女', 5 => '同学', 6 => '朋友', 7 => '同事', 8 => '亲戚', 9 => '儿子', 10 => '女儿', 11 => '兄弟', 12 => '姐妹', 100 => '其他'];

        if (isset($temp[$status])) {
            return $temp[$status];
        }

        return $temp[100];
    }
}
